﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using My.Framework.AspNetCore;

namespace My.Framework
{
	/// <summary>
	/// AspNetCore 服务启动程序
	/// </summary>
	public static class StartupApplication
    {
        /// <summary>
        /// 启动 AspNetCore 应用程序
        /// </summary>
        /// <typeparam name="TStartupModule"></typeparam>
        /// <param name="args"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static async Task RunAsync<TStartupModule>(string[] args)
            where TStartupModule : IStartupModule
        {
            var webApplicationBuilder = WebApplication.CreateBuilder(args);

            // 打印启动信息
            Console.WriteLine(@$"{webApplicationBuilder.Environment.ApplicationName} 启动! -- {DateTime.Now:yyyy-MM-dd HH:mm:ss}");

			// 注册 Startup 过滤器
			webApplicationBuilder.Services.AddTransient<IStartupFilter, StartupFilter>();

			// 加入StartupModule
			webApplicationBuilder.AddStartupModule<TStartupModule>();

			// 构建
			var webApplication = webApplicationBuilder.Build();

			App._host = webApplication;

			// 启动 app
			await webApplication.RunAsync();
		}
		
		/// <summary>
		/// 启动 AspNetCore 应用程序
		/// </summary>
		/// <param name="args"></param>
		/// <param name="options"></param>
		/// <typeparam name="TStartupModule"></typeparam>
		public static void Run<TStartupModule>(string[] args)
            where TStartupModule : IStartupModule
        {
            RunAsync<TStartupModule>(args).Wait();
        }
    }
}
